import com.drew.metadata.Directory
import com.drew.metadata.Metadata
import com.drew.metadata.MetadataReader
import com.drew.imaging.jpeg.JpegMetadataReader
import com.drew.metadata.jpeg.JpegDirectory

/**
 *
 * @author dmitryb
 */
class Exif {
  static Dimension getWidthAndHeight(Metadata metadata) {
    def jdir = metadata.getDirectory(JpegDirectory.class)
    if(jdir == null) {
      throw new IllegalArgumentException("Invalid file - could not find JPEG metadata")
    }

    if(!jdir.containsTag(JpegDirectory.TAG_JPEG_IMAGE_HEIGHT) || !jdir.containsTag(JpegDirectory.TAG_JPEG_IMAGE_WIDTH)) {
      throw new IllegalArgumentException("File must contain EXIF width and height")
    }

    // Retrieve width and height
    def imageWidth = jdir.getInt(JpegDirectory.TAG_JPEG_IMAGE_WIDTH)
    def imageHeight = jdir.getInt(JpegDirectory.TAG_JPEG_IMAGE_HEIGHT)

    return new Dimension(imageWidth, imageHeight)
  }

  static Dimension getWidthAndHeightFromFile(File f) {
    getWidthAndHeight(readMetadata(f))
  }

  static Metadata readMetadata(File f) {
    com.drew.imaging.ImageMetadataReader.readMetadata(f)
  }
}

